<?php

includePackage('Eip');
class StudentWebModule extends WebModule
{
    protected static $defaultModel = 'EipDataModel';
    protected $id = 'student';
    protected $feeds = array();
    protected $feed;
    protected $email;
    protected $identity;
    protected $position;
    protected $uid;
    protected $unit;
    protected $unitid;
    protected $fullname;

    protected function initialize() {
        $user = $this->getUser();
        $this->email = $user->getEmail();
        $this->identity = $user->getAttribute('identity');
        $this->position = $user->getAttribute('position');
        $this->uid = $user->getAttribute('uid');
        $this->unit = $user->getAttribute('unit');
        $this->unitid = $user->getAttribute('unitid');
        $this->ban = $user->getAttribute('ban');
        $this->fullname = $user->getFullname();
    }

    protected function getFeed($class = null) {
        $controller = DataModel::factory('EipDataModel', array('RETRIEVER_CLASS' => 'UrlEipRetriever', 'TYPE' => 'stud', 'BASE_URL' => '[YOUR_SERVER]', 'ARGS' => array('schname' => $this->unit, 'ban' => $class, 'quser' => $this->email)));

        return $controller;
    }

    private function getBanFromEip() {
        $controller = DataModel::factory('EipDataModel', array('RETRIEVER_CLASS' => 'UrlEipRetriever', 'TYPE' => 'ban', 'BASE_URL' => '[YOUR_SERVER]', 'ARGS' => array('sshcode' => $this->unitid, 'quser' => $this->email)));
        $items = $controller->items();

        $classes = array('' => '');
        foreach ($items as $item) {
            $classes[] = array(
                'value' => $item,
                'title' => $item
            );
        }
        return $classes;
    }

    private function getTeacherBanFormEip() {
        $uid = $this->email;
        $controller = DataModel::factory('EipDataModel', array('RETRIEVER_CLASS' => 'UrlEipRetriever', 'TYPE' => 'ban', 'BASE_URL' => '[YOUR_SERVER]', 'PARSER_CLASS' => 'JSONDataParser'));
        $items = $controller->items();

        $classes = array('' => '');
        foreach ($items as $item) {
            $classes[] = array(
                'value' => $item['clsno'],
                'title' => $item['clsno']
            );
        }

        return $classes;
    }

    private function getProfileFormEip($wid = null) {
        $controller = DataModel::factory('EipDataModel', array('RETRIEVER_CLASS' => 'UrlEipRetriever', 'PARSER_CLASS' => 'JSONDataParser', 'TYPE' => 'profile', 'BASE_URL' => '[YOUR_SERVER]'));
        $items = $controller->items();

        foreach ($items as $item) {
            $personDetails[''] = array(
                array('label' => '家長姓名', 'title' => $item['parent']),
                array('label' => '電話', 'title' => $item['tel']),
                array('label' => '地址', 'title' => $item['address']),
                array('label' => '生日', 'title' => $item['birthday']),
            );

            return $personDetails;      
        }
    }

    private function getAbsentFormEip($wid = null) {
        $controller = DataModel::factory('EipDataModel', array('RETRIEVER_CLASS' => 'UrlEipRetriever', 'TYPE' => 'absent', 'BASE_URL' => '[YOUR_SERVER]', 'ARGS' => array('wid' => $wid, 'quser' => $this->email)));

        $items = $controller->items();

        return $items;
    }

    private function getAbdatFormEip($wid = null) {
        $controller = DataModel::factory('EipDataModel', array('RETRIEVER_CLASS' => 'UrlEipRetriever', 'TYPE' => 'abdat', 'BASE_URL' => '[YOUR_SERVER]', 'ARGS' => array('wid' => $wid, 'quser' => $this->email)));

        $items = $controller->items();

        return $items;
    }

    private function getScoreFormEip($wid = null) {
        $controller = DataModel::factory('EipDataModel', array('RETRIEVER_CLASS' => 'UrlEipRetriever', 'TYPE' => 'score', 'BASE_URL' => '[YOUR_SERVER]', 'ARGS' => array('wid' => $wid, 'quser' => $this->email)));

        $items = $controller->items();

        return $items;
    }

    private function getSumFormEip($wid = null) {
        $controller = DataModel::factory('EipDataModel', array('RETRIEVER_CLASS' => 'UrlEipRetriever', 'PARSER_CLASS' => 'JSONDataParser', 'TYPE' => 'sum', 'BASE_URL' => '[YOUR_SERVER]'));

        $items = $controller->items();

        $entries = array();
        foreach ($items as $item) {
            $entries[] = array('label' => $item['scritem'], 'title' => $item['scr']);
        }

        return $entries;
    }

    public function searchItems($searchTerms, $limit=null, $options=null) {
        $start = isset($options['start']) ? $options['start'] : 0;

        $this->feed->setStart($start);
        $this->feed->setLimit($limit);

        return $this->feed->search($searchTerms);
    }

    protected function extractModuleArray($args, $flatten = false) {
        $return = array();
        if (isset($args['id'])) {
            $return['id'] = $args['id'];
        }

        if (isset($args['page'])) {
            $return['page'] = $args['page'];
        }

        if (isset($args['args'])) {
            if ($flatten && is_array($args['args'])) {
                foreach ($args['args'] as $arg=>$value) {
                    $return['args[' . $arg . ']'] = $value;
                }
            } else {
                $return['args'] = $args['args'];
            }
        }

        return $return;
    }

    protected function initializeForPage() {
        /**
         * no feed, throw exception
         */
        //if (count($this->feeds) == 0) {
        //    throw new KurogoConfigurationException("No student feeds configured");
        //}

        $authorityIndex = $this->getUser()->getAuthenticationAuthorityIndex();
        if (!$this->isLoggedIn() || ($authorityIndex <> 'eip' && $authorityIndex <> 'eip_parent'))
            $this->unauthorizedAccess();

        switch($this->page) {
            case 'index':
                if ($this->identity == '教師') {
                    $class = $this->getArg('class', '');

                    if ($this->unit == '教育處' || $this->position == '校長') {
                        $this->assign('classes', $this->getBanFromEip());
                    } else {
                        //$this->assign('classes', $this->getTeacherBanFormEip());
                        $this->assign('classes', array(array('value' => $this->ban, 'title' => $this->ban)));                 
                        $class = $this->ban;
                    }

                    $this->assign('currentClass', $class);

                    $searchTerms = $this->getArg('filter');
                    $this->assign('searchTerms', $searchTerms);

                    $students = array();
                    if ($class)
                    {
                        $this->feed = $this->getFeed($class);
                        if ($searchTerms) {
                            $items = $this->searchItems($searchTerms);
                        } else {
                            $items = $this->feed->items();
                        }

                        foreach($items as $item) {
                            $student = array();
                            $student['title'] = $item->getStudname();
                            $student['url'] = $this->buildBreadcrumbURL('detail', array('sid' => $item->getStudpky(), 'name' => $item->getStudname()), true);
                            $students[] = $student;
                        }
                    }

                    $this->assign('students', $students);

                    $extraArgs = array(
                        'class' => $class,
                    );
                    $this->assign('extraArgs', $extraArgs);
                } elseif ($this->identity == '學生') {
                    $this->redirectTo('detail');
                } else {
                    $this->unauthorizedAccess();
                }
                break;
            case 'detail':
                $defaultTab = null;

                //return URL
                $urlArray = $this->extractModuleArray($this->getArrayForRequest());
                $this->assign('urlArray', $this->extractModuleArray($urlArray, true));

                $password = $this->argVal($_POST, 'loginPassword', '');

                if (!empty($password)) {
                    $defaultTab = '基本資料';

                    $controller = DataModel::factory('EipDataModel', array('RETRIEVER_CLASS' => 'UrlEipRetriever', 'TYPE' => 'login', 'BASE_URL' => $this->getUser()->getAuthenticationAuthority()->getEipServer(), 'ARGS' => array('uid' => $this->email, 'pwd' => $password)));
                    $userData = $controller->items();
                    if (current($userData)) {
                        $expireTime = time() + 10;
                        setcookie('profile', 'test', $expireTime, COOKIE_PATH);
                        if ($urlArray) {
                            $this->redirectToArray($urlArray, Kurogo::REDIRECT_SEE_OTHER);
                        } else {
                            $this->redirectToModule($this->getHomeModuleID(),'',array('login'=>$authorityIndex), Kurogo::REDIRECT_SEE_OTHER);
                        }
                    } else {
                        $this->assign('message', '驗證失敗！');
                    }
                }

                if ($this->identity == '教師') {
                    $wid = $this->getArg('sid', 0);
                    $studentName = $this->getArg('name', '');
                } elseif ($this->identity == '學生') {
                    $wid = $this->uid;
                    $studentName = $this->fullname;
                } else {
                    $this->unauthorizedAccess();
                }

                $absents = $this->getAbsentFormEip($wid);
                $abdats = $this->getAbdatFormEip($wid);
                $scores = $this->getScoreFormEip($wid);
                $sums = $this->getSumFormEip($wid);
                $profiles = array('' => null);
                if (isset($_COOKIE['profile'])) {
                    $defaultTab = '基本資料';

                    $profiles = $this->getProfileFormEip($wid);
                }

                $studTabs = array(
                    '成績' => array(
                        'contents' => $scores
                    ),
                    '獎懲' => array(
                        'contents' => $abdats
                    ),
                    '出缺席' => array(
                        'contents' => $absents
                    ),
                    '分發比序' => array(
                        'contents' => $sums
                    ),
                    '十二年國教' => array(
                        'contents' => array(
                            array('title' => '國中生涯輔導手冊資料', 'url' => $this->buildBreadcrumbURL('download', array('sid' => $wid))),
                        )
                    ),
                );

                if ($this->identity == '教師') {
                    $studTabs['基本資料'] = array(
                        'contents' => $profiles['']
                    );
                }

                $this->enableTabs(array_keys($studTabs), $defaultTab);
                $this->assign('tabContents', $studTabs);

                $this->assign('studentName', $studentName);
                $this->assign('profileURL', $this->buildBreadcrumbURL('profile', array('sid' => $wid, 'name' => $studentName)));
                break;
            case 'profile':
                if (isset($_COOKIE['profile'])) {
                    if ($this->identity == '教師') {
                        $wid = $this->getArg('sid', 0);
                        $studentName = $this->getArg('name', '');
                    } else {
                        $this->unauthorizedAccess();
                    }
                    $personDetails = $this->getProfileFormEip($wid);
                    $this->assign('studentName', $studentName);
                    $this->assign('personDetails', $personDetails);
                } else {
                    $this->redirectTo('comfirm', $this->getArrayForRequest());
                }
                break;
            case 'comfirm':
                //return URL
                $urlArray = $this->extractModuleArray($this->args);
                $this->assign('urlArray', $this->extractModuleArray($urlArray, true));

                $password = $this->argVal($_POST, 'loginPassword', '');

                if (!empty($password)) {
                    $controller = DataModel::factory('EipDataModel', array('RETRIEVER_CLASS' => 'UrlEipRetriever', 'TYPE' => 'login', 'BASE_URL' => $this->getUser()->getAuthenticationAuthority()->getEipServer(), 'ARGS' => array('uid' => $this->email, 'pwd' => $password)));
                    $userData = $controller->items();
                    if (current($userData)) {
                        $expireTime = time() + 10;
                        setcookie('profile', 'test', $expireTime, COOKIE_PATH);
                        if ($urlArray) {
                            $this->redirectToArray($urlArray, Kurogo::REDIRECT_SEE_OTHER);
                        } else {
                            $this->redirectToModule($this->getHomeModuleID(),'',array('login'=>$authorityIndex), Kurogo::REDIRECT_SEE_OTHER);
                        }
                    } else {
                        $this->assign('message', '驗證失敗！');
                    }
                }
                break;
            case 'download':
                if ($this->identity == '教師') {
                    $wid = $this->getArg('sid', 0);
                } elseif ($this->identity == '學生') {
                    $wid = $this->uid;
                } else {
                    $this->unauthorizedAccess();
                }

                $pdf = fopen('[YOUR_SERVER]', 'r');
                $output = '';
                while (!feof($pdf)) {
                    $output .= fgets($pdf);
                }

                $temp = tmpfile();

                fwrite($temp, $output);
                fseek($temp, 0);

                $meta_data = stream_get_meta_data($temp);
                $filename = $meta_data["uri"];

                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename=' . 'file.pdf');
                header('Content-Transfer-Encoding: binary');
                header('Expires: 0');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                header('Pragma: public');
                header('Content-Length: ' . filesize($filename));
                ob_clean();
                flush();
                readfile($filename);

                fclose($temp);
                break;
        }
    }
}
